package com.eascs.web.o2o.report.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StopWatch;
import com.eascs.notify.email.entity.EmailSourceSetting;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.o2o.report.util.DateUtil;

@RestController
@RequestMapping("/excelDown")
public class ExcelDown extends BaseRestController {
	private final Logger logger = LoggerFactory.getLogger(ExcelDown.class);
	
	@Autowired
	EmailSourceSetting emailSourceSetting;
	
	@RequestMapping("/download")
	public BaseRestResult<String> dowanload(HttpServletResponse httpServletResponse,HttpServletRequest request,String type){
		BaseRestResult<String> result=null;
		StopWatch stopWatch = new StopWatch();
        	//输出路径
      		String path = emailSourceSetting.getFilepath();
      		StringBuffer s = new StringBuffer();
      		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      		String date = sdf.format(new Date());
      		//标题
      		int i= 1;
      		String yesterday=DateUtil.getSpecifiedDayBefore(i);//昨天时间
      		String fileAttach="";
      		 //  /opt/src/execl/2016-08-032016-08-02.xls
      		String outPath = s.append(path).append("/"+date).append(fileAttach).append(yesterday).append(".xls").toString();
        if(type.equals("1") ){
        	OutputStream os = null;
        	logger.debug("进入平台明细，共耗时：[{}]毫秒", stopWatch.elapsedTime());
			try {			
				fileAttach="/O2O金融业务台账——平台明细-";
				String outfile = fileAttach+yesterday+".xls";
				String userAgent = request.getHeader("User-Agent");
				byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
				outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
				s.setLength(0);
				outPath = s.append(path).append("/"+date).append(fileAttach).append(yesterday).append(".xls").toString();
				File f = new File(outPath);
				logger.debug("平台查询开始时间，共耗时：[{}]毫秒", stopWatch.elapsedTime());
				while(!f.exists()){
					//当前的前一天找不到报表文件，则再去推算上一天
					logger.debug("平台循环开始时间，共耗时：[{}]毫秒"+outPath, stopWatch.elapsedTime());
					date = DateUtil.getSpecifiedDayBefore(i);//昨天时间
					yesterday=DateUtil.getSpecifiedDayBefore(++i);//昨天时间
					s.setLength(0);
					outPath = s.append(path).append("/"+date).append(fileAttach).append(yesterday).append(".xls").toString();
					outfile = fileAttach+yesterday+".xls";
					userAgent = request.getHeader("User-Agent");
					if (userAgent.contains("MSIE"))
						outfile = java.net.URLEncoder.encode(outfile, "UTF-8");
					else{
						bytes = outfile.getBytes("UTF-8");
						outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
					}
					logger.debug("平台循环获取路径时间，共耗时：[{}]毫秒"+outPath, stopWatch.elapsedTime());
					f = new File(outPath);
					logger.debug("平台循环结束时间，共耗时：[{}]毫秒"+outPath, stopWatch.elapsedTime());
					if(date.equals("2016-01-01")){
						break;
					}
				}
				logger.debug("平台查询结束时间，共耗时：[{}]毫秒", stopWatch.elapsedTime());
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				IoUtil.fileToOutputStream(f, byteArrayOutputStream);
				os.write(byteArrayOutputStream.toByteArray());
				os.flush();
				logger.debug("平台明细下载任务结束，共耗时：[{}]毫秒", stopWatch.elapsedTime());
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
        }else{
        	logger.debug("进入省区明细，共耗时：[{}]毫秒", stopWatch.elapsedTime());
        	OutputStream os = null;
			try {			
				fileAttach="/O2O金融业务台账——省区明细-";
				String outfile = fileAttach+yesterday+".xls";
				String userAgent = request.getHeader("User-Agent");
				byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
				outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
				s.setLength(0);
				outPath = s.append(path).append("/"+date).append(fileAttach).append(yesterday).append(".xls").toString();
				File f = new File(outPath);
				logger.debug("省区查询开始时间，共耗时：[{}]毫秒", stopWatch.elapsedTime());
				while(!f.exists()){
					logger.debug("省区循环开始时间，共耗时：[{}]毫秒"+outPath, stopWatch.elapsedTime());
					//当前的前一天找不到报表文件，则再去推算上一天
					date = DateUtil.getSpecifiedDayBefore(i);//昨天时间
					yesterday=DateUtil.getSpecifiedDayBefore(++i);//昨天时间
					s.setLength(0);
					outPath = s.append(path).append("/"+date).append(fileAttach).append(yesterday).append(".xls").toString();
					outfile = fileAttach+yesterday+".xls";
					userAgent = request.getHeader("User-Agent");
					if (userAgent.contains("MSIE"))
						outfile = java.net.URLEncoder.encode(outfile, "UTF-8");
					else{
						bytes = outfile.getBytes("UTF-8");
						outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
					}
					logger.debug("省区循环获取路径时间，共耗时：[{}]毫秒"+outPath, stopWatch.elapsedTime());
					f = new File(outPath);
					logger.debug("省区循环结束时间，共耗时：[{}]毫秒"+outPath, stopWatch.elapsedTime());
					if(date.equals("2016-01-01")){
						break;
					}
				}
				logger.debug("省区查询结束时间，共耗时：[{}]毫秒", stopWatch.elapsedTime());
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				IoUtil.fileToOutputStream(f, byteArrayOutputStream);
				os.write(byteArrayOutputStream.toByteArray());
				os.flush();
				logger.debug("省区明细下载任务结束，共耗时：[{}]毫秒", stopWatch.elapsedTime());
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
        	
        }
		return result;
	}

}
